import compress from '@/components/w-compress/compress.js'
//图片压缩
function imgCompress(imUrl) {
	return new Promise((resolve, reject) => {
		compress(imUrl).then(res => {
				var arr = res.split(','),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				resolve((window.URL || window.webkitURL).createObjectURL(new Blob([u8arr], {
					type: mime
				})));
			})
			.catch(e => {
				console.log(e)
			})
	});
}
// 天时分秒倒计时
function timeCount(valid_time, day) {
	let timestamp = Date.parse(new Date()) / 1000;
	let time = valid_time - timestamp
	let d
	let h
	if (day) {
		d = parseInt(time / 86400)
		h = parseInt((time % 86400) / 3600)
	} else {
		h = parseInt(time / 3600)
	}
	let m = parseInt((time % 3600) / 60)
	let s = time % 60
	h = h < 10 ? (`0${h}`) : h
	m = m < 10 ? (`0${m}`) : m
	s = s < 10 ? (`0${s}`) : s
	let countdownTime
	if (time > 0) {
		if (day) {
			countdownTime = d + "天 " + h + ":" + m + ":" + s
		} else {
			countdownTime = h + ":" + m + ":" + s
		}

	} else {
		countdownTime = "00:00:00"
	}
	return countdownTime
}
// 数字千位分割
function format(num) {
	num = num.toString().split("."); // 分隔小数点
	var arr = num[0].split("").reverse(); // 转换成字符数组并且倒序排列
	var res = [];
	for (var i = 0, len = arr.length; i < len; i++) {
		if (i % 3 === 0 && i !== 0) {
			res.push(","); // 添加分隔符
		}
		res.push(arr[i]);
	}
	res.reverse(); // 再次倒序成为正确的顺序
	if (num[1]) { // 如果有小数的话添加小数部分
		res = res.join("").concat("." + num[1]);
	} else {
		res = res.join("");
	}
	return res;
}
//输入框首位小数点，首位0，不能超过两位小数规范
function verifyNum(number) {
	let num = number.toString()
	if (num.indexOf(".") == 0) {
		//'首位小数点情况'
		num = num.replace(/[^$#$]/g, "0.");
	} else if (num.indexOf("0") == 0 && num >= 1) {
		//首位0情况
		num = num.replace("0", "");
	} else if (!(/^(\d?)+(\.\d{0,2})?$/.test(num))) {
		//去掉最后一位
		num = num.substring(0, num.length - 1)
	}
	return num
}
// js浮点计算不准确
function accMul(arg1, arg2) {
	var m = 0,
		s1 = arg1.toString(),
		s2 = arg2.toString();
	try {
		m += s1.split(".")[1].length;
	} catch (e) {}
	try {
		m += s2.split(".")[1].length;
	} catch (e) {}
	return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

// 隐藏号码中间几位
function hidden(str, frontLen, endLen) {
	var len = str.length - frontLen - endLen;
	var xing = '';
	for (var i = 0; i < len; i++) {
		xing += '*';
	}
	return str.substring(0, frontLen) + xing + str.substring(str.length - endLen);
}
// 二维码参数获取
function urlDecode(option) {
	let string1 = decodeURIComponent(decodeURIComponent(option.scene))
	string1 = '{"' + string1.replace(/=/g, '":').replace(/&/g, ',"') + '}'
	let string = JSON.parse(string1)
	return string;
}

module.exports = {
	hidden: hidden,
	urlDecode: urlDecode,
	accMul: accMul,
	verifyNum: verifyNum,
	timeCount: timeCount,
	format: format,
	imgCompress: imgCompress
}
